from fastapi import APIRouter, Depends, HTTPException, Query
from typing import List, Optional

from app.core.deps import get_current_active_user
from app.models.models import User, Role, Permission, RolePermission, UserRole
from app.schemas.role import RoleCreate, RoleUpdate, RoleOut
from app.schemas.base import ResponseBase, PageResponseBase, PageInfo

router = APIRouter()

@router.get("/", response_model=PageResponseBase[List[RoleOut]])
async def get_roles(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页条数"),
    name: Optional[str] = Query(None, description="角色名称"),
    code: Optional[str] = Query(None, description="角色编码"),
    status: Optional[bool] = Query(None, description="状态"),
    _: User = Depends(get_current_active_user)
):
    """获取角色列表"""
    # 构建查询条件
    query = {}
    if name:
        query["name__contains"] = name
    if code:
        query["code__contains"] = code
    if status is not None:
        query["status"] = status
    
    # 查询总数
    total = await Role.filter(**query).count()
    
    # 分页查询
    roles = await Role.filter(**query).offset((page - 1) * page_size).limit(page_size).all()
    
    # 构建角色列表
    role_list = []
    for role in roles:
        # 获取角色权限 - 通过关联表查询
        role_perm_relations = await RolePermission.filter(role_id=role.id).prefetch_related('permission').all()
        permissions = []
        for relation in role_perm_relations:
            perm = relation.permission
            permissions.append({"id": perm.id, "name": perm.name, "code": perm.code})
        
        # 构建角色信息
        role_data = {
            "id": role.id,
            "name": role.name,
            "code": role.code,
            "description": role.description,
            "status": role.status,
            "permissions": permissions,
            "created_at": role.created_at,
            "updated_at": role.updated_at
        }
        
        role_list.append(RoleOut(**role_data))
    
    # 构建分页信息
    page_info = PageInfo(page=page, page_size=page_size, total=total)
    
    return PageResponseBase[List[RoleOut]](
        data=role_list,
        page_info=page_info
    )

@router.post("/", response_model=ResponseBase[RoleOut])
async def create_role(
    role_in: RoleCreate,
    _: User = Depends(get_current_active_user)
):
    """创建角色"""
    # 检查角色名称是否已存在
    if await Role.filter(name=role_in.name).exists():
        raise HTTPException(status_code=400, detail="角色名称已存在")
    
    # 检查角色编码是否已存在
    if await Role.filter(code=role_in.code).exists():
        raise HTTPException(status_code=400, detail="角色编码已存在")
    
    # 创建角色
    role = await Role.create(
        name=role_in.name,
        code=role_in.code,
        description=role_in.description,
        status=role_in.status
    )
    
    # 添加权限
    if role_in.permission_ids:
        for permission_id in role_in.permission_ids:
            await RolePermission.create(role_id=role.id, permission_id=permission_id)
    
    # 获取角色权限 - 通过关联表查询
    role_perm_relations = await RolePermission.filter(role_id=role.id).prefetch_related('permission').all()
    permissions = []
    for relation in role_perm_relations:
        perm = relation.permission
        permissions.append({"id": perm.id, "name": perm.name, "code": perm.code})
    
    # 构建角色信息
    role_data = {
        "id": role.id,
        "name": role.name,
        "code": role.code,
        "description": role.description,
        "status": role.status,
        "permissions": permissions,
        "created_at": role.created_at,
        "updated_at": role.updated_at
    }
    
    return ResponseBase[RoleOut](data=RoleOut(**role_data))

@router.get("/{role_id}", response_model=ResponseBase[RoleOut])
async def get_role(
    role_id: int,
    _: User = Depends(get_current_active_user)
):
    """获取角色详情"""
    role = await Role.filter(id=role_id).first()
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 获取角色权限 - 通过关联表查询
    role_perm_relations = await RolePermission.filter(role_id=role.id).prefetch_related('permission').all()
    permissions = []
    for relation in role_perm_relations:
        perm = relation.permission
        permissions.append({"id": perm.id, "name": perm.name, "code": perm.code})
    
    # 构建角色信息
    role_data = {
        "id": role.id,
        "name": role.name,
        "code": role.code,
        "description": role.description,
        "status": role.status,
        "permissions": permissions,
        "created_at": role.created_at,
        "updated_at": role.updated_at
    }
    
    return ResponseBase[RoleOut](data=RoleOut(**role_data))

@router.put("/{role_id}", response_model=ResponseBase[RoleOut])
async def update_role(
    role_id: int,
    role_in: RoleUpdate,
    _: User = Depends(get_current_active_user)
):
    """更新角色"""
    role = await Role.filter(id=role_id).first()
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 检查角色名称是否已存在
    if role_in.name and role_in.name != role.name:
        if await Role.filter(name=role_in.name).exists():
            raise HTTPException(status_code=400, detail="角色名称已存在")
    
    # 检查角色编码是否已存在
    if role_in.code and role_in.code != role.code:
        if await Role.filter(code=role_in.code).exists():
            raise HTTPException(status_code=400, detail="角色编码已存在")
    
    # 更新角色信息
    update_data = role_in.dict(exclude_unset=True)
    
    if "permission_ids" in update_data:
        permission_ids = update_data.pop("permission_ids")
        # 清空原有权限
        await RolePermission.filter(role_id=role.id).delete()
        # 添加新权限
        if permission_ids:
            for permission_id in permission_ids:
                await RolePermission.create(role_id=role.id, permission_id=permission_id)
    
    # 更新角色
    await role.update_from_dict(update_data)
    await role.save()
    
    # 获取角色权限 - 通过关联表查询
    role_perm_relations = await RolePermission.filter(role_id=role.id).prefetch_related('permission').all()
    permissions = []
    for relation in role_perm_relations:
        perm = relation.permission
        permissions.append({"id": perm.id, "name": perm.name, "code": perm.code})
    
    # 构建角色信息
    role_data = {
        "id": role.id,
        "name": role.name,
        "code": role.code,
        "description": role.description,
        "status": role.status,
        "permissions": permissions,
        "created_at": role.created_at,
        "updated_at": role.updated_at
    }
    
    return ResponseBase[RoleOut](data=RoleOut(**role_data))

@router.delete("/{role_id}", response_model=ResponseBase)
async def delete_role(
    role_id: int,
    _: User = Depends(get_current_active_user)
):
    """删除角色"""
    role = await Role.filter(id=role_id).first()
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 检查角色是否被用户使用
    user_role_count = await UserRole.filter(role_id=role.id).count()
    if user_role_count > 0:
        raise HTTPException(status_code=400, detail="角色已被用户使用，无法删除")
    
    # 删除角色
    await role.delete()
    
    return ResponseBase()